using Newtonsoft.Json.Linq;

namespace my_console5;

public class AggOutput2
{
    public static JArray Parse(JToken token)
    {
        var obj = IterateToken(token);
        File.WriteAllText("agg.json", obj.ToString());
        return null;
    }

    static JObject IterateToken(JToken token, string field = "buckets")
    {
        var properties = token.Children<JProperty>();
        if (!properties.Any())
            return null;
        var child = new JObject();
        foreach (var property in properties)
        {
            var fieldName = property.Name;
            var fieldValue = property.Value;
            if (fieldName == "key_as_string")
            {
                child["key"] = fieldValue;
            }
            else if (fieldName == "key" && !child.ContainsKey("key"))
            {
                child["key"] = fieldValue;
            }
            else if (fieldName == "doc_count")
            {
                child["count"] = fieldValue;
            }
            if (fieldValue is not JObject)
                continue;
            var value = fieldValue[field];
            if (value == null)
                continue;
            var list = new JArray();
            if (value is JArray array)
            {
                foreach (var item in array)
                {
                    list.Add(IterateToken(item));
                }
            }
            child[fieldName] = list;
        }
        return child;
    }

    


}
